<template>
  <span>{{target}}</span>
</template>

<script>
export default {
  name: 'IncreaseComponent',
  props: {
    // 初始值
    initialValue: {
      type: Number,
      default: 0
    },
    // 目标值
    targetValue: {
      type: Number,
      default: 0
    },
    // ms, 默认2000，表示2秒完成递增
    delay: {
      type: Number,
      default: 2000
    }
  },
  data () {
    return {
      target: this.targetValue,
      timer: null,
      count: 0
    }
  },
  watch: {
    targetValue: {
      handler: function (val) {
        if (val) {
          if (this.timer) {
            clearInterval(this.timer)
            this.timer = null
            this.count = 0
          }
          this.target = this.initialValue
          // 0.1秒递增一次
          const times = this.delay / 100
          // 每次整数递增
          const oneStep = Math.ceil((val - this.initialValue) / times)
          this.timer = setInterval(() => {
            this.count++
            if (this.count === times) {
              clearInterval(this.timer)
              this.target = val
            } else {
              this.target += oneStep
            }
          }, times)
        } else {
          this.target = 0
        }
      },
      immediate: true
    }
  }
}
</script>

<style scoped>

</style>
